package com.dunqi.gpm.shunqing.home.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseViewHolder;
import com.dunqi.gpm.shunqing.R;
import com.dunqi.gpm.shunqing.common.api.ApiFactory;
import com.dunqi.gpm.shunqing.common.api.RxSchedulers;
import com.dunqi.gpm.shunqing.common.base.BaseAct;
import com.dunqi.gpm.shunqing.common.base.Data;
import com.dunqi.gpm.shunqing.common.base.RecyclerAdapter;
import com.dunqi.gpm.shunqing.common.util.CommonUtil;
import com.dunqi.gpm.shunqing.common.util.SwipeUtil;
import com.dunqi.gpm.shunqing.common.view.RecyclerItemDecoration;
import com.dunqi.gpm.shunqing.home.bean.EarlyInfo;
import com.dunqi.gpm.shunqing.home.bean.Project;
import com.dunqi.gpm.shunqing.home.constance.Constance;
import com.dunqi.gpm.shunqing.home.widget.EmptyView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import io.reactivex.functions.Consumer;

public class AddEarlyActivity extends BaseAct implements SwipeRefreshLayout.OnRefreshListener {

    List<EarlyInfo> data = new ArrayList<>();
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefresh;
    @BindView(R.id.commit_tv)
    TextView commitTv;

    private Project project;
    private UnSelectedAdapter adapter;

    @Override
    protected void refreshData(Bundle savedInstanceState) {
        net();
    }

    private void net() {
        HashMap<String, String> param = new HashMap<>();
        param.put("project_id", String.valueOf(project.getProjectId()));
        param.put("plan_year", String.valueOf(project.getPlanYear()));
        param.put("plan_id", String.valueOf(project.getProAnnualPlanId()));

        ApiFactory.getInstance()
                .getUnSelected(param)
                .compose(RxSchedulers.<Data<ArrayList<EarlyInfo>>>io_main())
                .subscribe(new Consumer<Data<ArrayList<EarlyInfo>>>() {
                    @Override
                    public void accept(Data<ArrayList<EarlyInfo>> arrayListData) throws Exception {
                        ArrayList<EarlyInfo> EarlyInfos = arrayListData.getData();
                        adapter.replaceData(EarlyInfos);
//                        data.clear();
//                        data.addAll(EarlyInfos);
//                        adapter.notifyDataSetChanged();

                        SwipeUtil.loadCompleted(swipeRefresh);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        SwipeUtil.loadCompleted(swipeRefresh);
                    }
                });
    }

    @Override
    protected void initUiAndListener() {
        project = (Project) getIntent().getSerializableExtra(Constance.PROJECT);

        SwipeUtil.init(swipeRefresh);
        adapter = new UnSelectedAdapter(data);
        recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        recycler.setAdapter(adapter);
        adapter.setEmptyView(new EmptyView(getActivity()));
        recycler.addItemDecoration(new RecyclerItemDecoration(1, RecyclerItemDecoration.VERTICAL));
        swipeRefresh.setOnRefreshListener(this);

        commitTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commit();
            }

        });
    }

    private void commit() {
        ArrayList<String> ids = new ArrayList<>();
        for (EarlyInfo datum : data) {
            if (datum.isSelected()) {
                ids.add(String.valueOf(datum.getPrepareStageDefId()));
            }
        }

        if (ids.isEmpty()) {
            CommonUtil.showSingleToast("请至少选择一个再提交");
            return;
        }

        HashMap<String, String> param = new HashMap<>();
        param.put("project_id", String.valueOf(project.getProjectId()));
        param.put("plan_year", String.valueOf(project.getPlanYear()));
        param.put("plan_id", String.valueOf(project.getProAnnualPlanId()));

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < ids.size(); i++) {
            String id = ids.get(i);
            sb.append(id);
            if (i != ids.size() - 1) {
                sb.append(",");
            }
        }
        param.put("add_stage_def_ids", sb.toString());
        param.put("return_all_after_add", String.valueOf(false));

        final ProgressDialog dialog = ProgressDialog.show(this, "提示","正在保存");

        ApiFactory.getInstance()
                .batchAdd(param)
                .compose(RxSchedulers.<Data>io_main())
                .subscribe(new Consumer<Data>() {
                    @Override
                    public void accept(Data data) throws Exception {
                        CommonUtil.showSingleToast("保存成功");
                        setResult(500);
                        finish();
                        dialog.dismiss();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dialog.dismiss();
                        CommonUtil.showSingleToast("保存失败");
                    }
                });


    }

    @Override
    public void onRefresh() {
        net();
    }

    class UnSelectedAdapter extends RecyclerAdapter<EarlyInfo> {

        public UnSelectedAdapter(@Nullable List<EarlyInfo> data) {
            super(R.layout.item_unselector_early, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, final EarlyInfo item) {

            final CheckBox checkBox = helper.getView(R.id.checked_cb);
            checkBox.setChecked(item.isSelected());

            helper.setText(R.id.name_tv, item.getStageName());
            helper.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean b = !checkBox.isChecked();
                    item.setSelected(b);
                    checkBox.setChecked(b);
                }
            });
        }
    }

    public static void start(Activity context, Project project) {
        Intent intent = new Intent(context, AddEarlyActivity.class);
        intent.putExtra(Constance.PROJECT, project);
        context.startActivityForResult(intent,652);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_project;
    }
}
